package commonwebgroup.commonwebartifact.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import commonwebgroup.commonwebartifact.Models.ApiResModel;
import org.bukkit.entity.Player;
import org.bukkit.util.Consumer;

import java.util.Objects;

/**
 * @author: wuxin0011
 * @Description:
 */
public class ResponseUtil {
    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 处理附带返回的结果过
     *
     * @param jsonStr response json str
     * @param c       class type
     * @param player  player
     * @param success (apiResModel)->{}
     * @param error   (string)->{}
     * @param <T>     T
     */
    public static <T extends ApiResModel> void validResponse(String jsonStr, Class<T> c, Player player, Consumer<T> success, Consumer<String> error) {
        try {
            Objects.requireNonNull(player, "player is not allow  null");
            Objects.requireNonNull(success, "success is not allow  null");
            Objects.requireNonNull(error, "success is not allow  null");
        } catch (Exception e) {
            error.accept(e.getMessage());
        }
        T t = null;
        try {
            t = GSON.fromJson(jsonStr, c);
        } catch (JsonSyntaxException e) {
            error.accept(e.getMessage());
            return;
        }

        if (t == null) {
            error.accept("json result is null");
            return;
        }
        // success
        if (t.isSuccess()) {
            // 成功执行的回调
            success.accept(t);
        } else {
            // 失败执行的回调
            error.accept(t.getMessage());
        }
    }
}
